package com.power.sifa.correction.dao.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.plf.core.common.dao.OffersetTransformers;
import com.power.sifa.correction.dao.Cre_work_recordDaoCustom;
import com.power.sifa.correction.model.Cre_work_record;
import com.power.sifa.correction.model.pageInfo.Cre_work_recordPageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.query.internal.NativeQueryImpl;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 处置记录 持久层实现(hibernate)
 */
@Slf4j
@Repository
public class Cre_work_recordDaoImpl implements Cre_work_recordDaoCustom {

    private final EntityManager entityManager;

    public Cre_work_recordDaoImpl(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    @Override
    public List queryList(Cre_work_recordPageInfo pageInfo) {
        List<Cre_work_record> result = new ArrayList<>();

        StringBuffer sql = new StringBuffer("select a.*, b.fullname from cre_work_record a left join ha_user b on a.userid = b.userid" +
                " where 1 = 1 ");
        List<Object> paramsList = new ArrayList<>();
        int index = 1;
        // 姓名查询
        if (StringUtils.isNotEmpty(pageInfo.getF_userid())) {
            sql.append(" and a.userid = ?" + index++);
            paramsList.add(pageInfo.getF_userid());
        }
        // 预警任务id
        if (StringUtils.isNotEmpty(pageInfo.getF_workid())) {
            sql.append(" and a.workid = ?" + index++);
            paramsList.add(pageInfo.getF_workid());
        }
        // 排序
        sql.append(" order by a.exectime desc");
        Query query = entityManager.createNativeQuery(sql.toString());
        query.unwrap(NativeQueryImpl.class).setResultTransformer(OffersetTransformers.ALIAS_TO_ENTITY_MAP);
        log.info(sql.toString());

        // 添加条件
        for (int i = 0; i <= paramsList.size() - 1; i++) {
            query.setParameter(i + 1, paramsList.get(i));
        }
        // 查询总数
        pageInfo.setAllcount(query.getResultList().size());
        // 分页
        if (pageInfo.getAllcount() > 0) {
            int pageStart = (pageInfo.getPageNumber() - 1) * pageInfo.getPageSize();
            List<Map> list = query.setFirstResult(pageStart).setMaxResults(pageInfo.getPageSize()).getResultList();
            if (CollectionUtil.isNotEmpty(list)) {
                result = JSON.parseArray(JSON.toJSONString(list), Cre_work_record.class);
            }
        }
        return result;
    }
}
